<?PHP
/**
 * $Rev: 13 $
 * $Id: application.php 13 2013-03-18 16:00:24Z vad.oparin@gmail.com $
 */

// including parent class
require_once ROOT . '/lib/singleton.php';

class application extends singleton {
	protected $classesLocations = array();
	protected $routes;
	protected $defaultRoute;

	public $controller;
	public $dispatcher;

	public function getRouteFormat() {
		return $this->routes['format'];
	}
	
	public function getDefaultRoute() {
		return $this->defaultRoute;
	}

	public function autoload($className) {
		$filename = $className . '.php';
		foreach ($this->classesLocations as $classesLocation) {
			if (file_exists($classesLocation . $filename)) {
				include $classesLocation . $filename;
			}
		}
	}

	public static function app() {
		return parent::getInstance();
	}

	public function registerModule($module) {
		$moduleDir = APP_ROOT . '/app/modules/' . $module;
		if (is_dir($moduleDir)) {
			$this->classesLocations[] = $moduleDir . '/controllers';
			return true;
		} else {
			return false;
		}
	}

	public function loadConfig() {
		$config = yaml_parse_file(APP_ROOT . '/etc/application.yaml');
		if ($config['routes']) {
			$this->routes = $config['routes'];
		} else {
			$this->routes = array('format' => 'query', );
		}
		// @formatter:off
		list($this->defaultRoute['module'], $this->defaultRoute['controller'], $this->defaultRoute['action'])
			= explode('/', ($config['defaultRoute']) ? $config['defaultRoute'] : 'frontend/main/index');
        // @formatter:on
	}

	public function __construct() {
		$this->classesLocations[] = ROOT . '/lib/';
		// @formatter:off
        spl_autoload_register(array($this, 'autoload'));
        // @formatter:on
	}

	public function init() {
		$this->loadConfig();
		$this->dispatcher = new dispatcher($this);
		$this->dispatcher->init()->delegate();
	}

}
